<script setup lang="ts">
import { nextTick, onMounted, watch } from 'vue'
import { useMapInit } from '@/hooks/useMapInit'
import { useCommon } from '@/hooks/useCommon'
import { useMarker } from '@/hooks/useMarker'
import { usePolygon } from '@/hooks/usePolygon'
import { usePolygonRange } from '@/hooks/usePolygonRange'
import { usePipe } from '@/hooks/usePipe'

const props = defineProps({
  recordData: {
    type: Object,
    default: () => ({}),
  },
  scopePolygonData: {
    type: Object,
    default: () => [{}],
  },
})
const emits = defineEmits(['addPolyline', 'deleteline', 'polygonCreated', 'updatePolygonRange'])

const { initMap, mapInstance, AMap, mouseTool, satellite } = useMapInit('mapId')
// 地图常用操作方法
const { changeMapType, locateCurrentPosition } = useCommon({ AMap, mapInstance, satellite })

// 初始化各个图层控制钩子
const { markers, clearMarkers, updateMarkers, onClickMarker, submitPipeline, cancelPipeline, offClickMarker } = useMarker({ AMap, mapInstance, emits })
const { polygons, clearPolygons, updatePolygons, openDrawPolygon, submitPolygon, cancelDrawPolygon } = usePolygon({ AMap, mapInstance, emits })
const { pipes, clearPipes, updatePipes, onDeletePipe, openClickPipe, closeClickPipe } = usePipe({ AMap, mapInstance, emits })
const { polygonsrange, clearPolygonRange, updatePolygonRange, openDrawPolygonRange, submitPolygonRange, cancelDrawPolygonRange } = usePolygonRange({ AMap, mapInstance, emits })

// 调整地图视野以显示所有元素
function fitMapView() {
  if (!mapInstance.value)
    return

  const allOverlays = [
    ...markers.value,
    ...polygons.value,
    ...pipes.value,
    ...polygonsrange.value,
  ]

  if (allOverlays.length > 0) {
    mapInstance.value.setFitView(allOverlays, false, [100, 200, 50, 110], 20)
  }
}

function initMapData(newData) {
  // 先清空所有图层
  clearMarkers()
  clearPolygons()
  clearPipes()
  clearPolygonRange()

  // 更新各类图层（只渲染接口返回的数据）
  // 出门井
  if (newData.exitWells?.length) {
    updateMarkers(newData.exitWells, 'exit')
  }
  // 接户井
  if (newData.connectWells?.length) {
    updateMarkers(newData.connectWells, 'connect')
  }
  // 市政井
  if (newData.municipalWells?.length) {
    updateMarkers(newData.municipalWells, 'municipal')
  }
  // 一级区域
  if (newData.firstAreas?.length) {
    updatePolygons(newData.firstAreas)
  }
  // 二级区域
  if (newData.secondAreas?.length) {
    updatePolygons(newData.secondAreas)
  }
  // 管线
  if (newData.lines?.length) {
    updatePipes(newData.lines)
  }
  // 排查范围
  if (props.scopePolygonData?.length) {
    updatePolygonRange(props.scopePolygonData)
  }
  // 调整视野
  nextTick(() => {
    fitMapView()
  })
}

// 监听数据变化，更新地图
watch(() => props.recordData, (newData) => {
  if (!newData)
    return

  // 检查 AMap 和 Polygon 是否可用
  if (!AMap.value || !AMap.value.Polygon) {
    console.warn('AMap or Polygon is not available yet')
    // 添加延迟，确保 AMap 对象已经完全初始化
    setTimeout(() => {
      initMapData(newData)
    }, 500)
  }
  else {
    initMapData(newData)
  }
}, { deep: true })

function reloadMap() {
  clearMarkers()
  clearPolygons()
  clearPipes()
}

onMounted(() => {
  initMap(() => {
    reloadMap()
  })
})

defineExpose({
  changeMapType,
  locateCurrentPosition,
  onClickMarker,
  submitPipeline,
  cancelPipeline,
  onDeletePipe,
  openClickPipe,
  closeClickPipe,
  offClickMarker,
  openDrawPolygon,
  submitPolygon,
  cancelDrawPolygon,
  openDrawPolygonRange,
  submitPolygonRange,
  cancelDrawPolygonRange,
})
</script>

<template>
  <div id="mapId" class="h-full w-full" />
</template>
